<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 17-11-15
 * Time: 上午11:10
 */

namespace workin\behaviors;


use workin\models\User;
use yii\base\ErrorException;
use yii\filters\AccessControl;

class Access extends AccessControl
{
    public function beforeAction($action)
    {
        $u_id = \Yii::$app->request->get('u_id');
        if (\Yii::$app->user->isGuest){
            return $this->_login($u_id);
        }else{
            if (\Yii::$app->user->id != $u_id){
                \Yii::$app->user->logout();
                return $this->_login($u_id);
            }
        }
        // http://192.168.1.102:9114/test/test/test?u_name=admin&u_password=1cdbcc81286d6084e60dd359bf04c750
//        \Yii::$app->user->loginUrl = ['site/login', 'u_name'=>$u_name, 'u_password'=>'1cdbcc81286d6084e60dd359bf04c750'];
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    public function afterAction($action, $result)
    {
        $u_id = \Yii::$app->request->get('u_id');
        if (!$u_id&&\Yii::$app->user->id){
            \Yii::$app->user->logout();
        }
        return parent::afterAction($action, $result); // TODO: Change the autogenerated stub
    }

    private function _login($u_id){
        if (!$u_id){
            throw new ErrorException("参数错误");
        }
        $user = User::findOne(['u_id'=>$u_id]);
        if (!$user){
            throw new ErrorException("没有找到用户");
        }
        if (!\Yii::$app->user->login($user, 3600)){
            throw new ErrorException("登录失败");
        }
    }
}